package com.wxw.gulidemo.controller;/**
 * @author by xxz
 * @date 2022/6/15
 */

import com.wxw.gulidemo.R;
import com.wxw.gulidemo.service.MsmService;
import com.wxw.gulidemo.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Description

 * @author by xxz

 * @date 2022/6/15

 * @throws
 */
@RestController
@CrossOrigin
@RequestMapping("/msmService/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/sendMsm/{phone}")
    public R sendMsm(@PathVariable String phone){
        //从redis获取验证码，如果能获取，直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //获取不到就阿里云发送
        //生成随机值，并传递给阿里云短信，让他转发给手机
        code = RandomUtils.getSixBitRandom();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);

        boolean isSend = msmService.sendMsm(map, phone);
        //如果短信发送成功,将验证码存到redis并设置过期时间为5min
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("短信发送失败");
        }

    }
}
